package com.aft.terra.common.interceptor;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.aft.terra.app.Constants;
import com.aft.terra.modules.game.model.GameDetails;
import com.aft.terra.modules.game.model.Intercept;
import com.aft.terra.modules.game.model.User;
import com.aft.terra.modules.member.model.Wechat;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;

public class VerificationGameQualificationsInterceptor implements Interceptor {

	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		String userId = controller.getCookie(Constants.SESSION_NAME);
		LogKit.info("VerificationGameQualificationsInterceptor ---------------------");
		if (StringUtils.isBlank(userId)) {
			controller.redirect("/");
			return;
		} else {
			User user = User.dao.queryUser(userId);
			if(user!=null){
				Long uId = user.getId();
				if (Intercept.dao.queryUserIdExistence(uId)) {
					controller.setAttr("message", "你违反了游戏规则");
					controller.render("/index.html");
					return;
				}
//				String wechatAgent = controller.getRequest().getHeader("User-Agent");
//				LogKit.info(wechatAgent);
//				if(wechatAgent.toLowerCase().indexOf("micromessenger")==-1){
//					Intercept intercept = new Intercept();
//					intercept.setUserId(uId);
//					intercept.setCreateDate(new Date());
//					intercept.setRemark("程序暴力破解");
//					intercept.setIp(Wechat.dao.findById(user.getWechatId()).getWLastLoginIp());
//					intercept.save();
//					controller.redirect("/");
//					return;
//				}
				Integer userGameCount = GameDetails.dao.queryCount(userId);// 游戏次数
				if ((userGameCount + user.getPlayGameFrequency()) != user.getGameFrequencySum()) {
					Intercept intercept = new Intercept();
					intercept.setUserId(uId);
					intercept.setCreateDate(new Date());
					intercept.setRemark("违反游戏规则，业务数据不一致");
					intercept.setIp(Wechat.dao.findById(user.getWechatId()).getWLastLoginIp());
					intercept.save();
					controller.setAttr("message", "你违反了游戏规则");
					controller.render("/index.html");
					return;
				}	
			}else{
				controller.redirect("/");
				return;
			}
			
		}
		inv.invoke();
	}

}
